<?php
class Tag_service {
	
	private $ci;
	
	public function __construct()
	{
		$this->ci = & get_instance();
		$this->ci->load->model('tag_model');
		$this->ci->load->model('record_model');
	}
	
	public function update_tag($user_id, $tag_id, $tag_name)
	{
		//authenticate
		$tag = $this->ci->tag_model->get_tag_by_id($tag_id);
		if(!$tag || $tag->userId != $user_id) return false;
		
		//change record tag name
		$this->ci->record_model->change_record_tag($user_id, $tag->tagName, $tag_name);	
		
		//get tag with new tag name
		$new_name_tag = $this->ci->tag_model->get_tag_by_name($user_id, $tag_name);
		if($new_name_tag)
		{
			$this->ci->tag_model->plus_count($user_id, $tag_name, $tag->tagCount);
			$this->ci->tag_model->del_tag($tag_id);
		}
		else
		{
			$this->ci->tag_model->update_tag($tag_id, $tag_name);
		}
	}

	public function del_tag($user_id, $tag_id)
	{
		//authenticate
		$tag = $this->ci->tag_model->get_tag_by_id($tag_id);
		if(!$tag || $tag->userId != $user_id) return false;
		
		//change record tag name
		$this->ci->record_model->change_record_tag($user_id, $tag->tagName, '');
		
		//del tag
		$this->ci->tag_model->del_tag($tag->tagId);
	}
}
?>